package org.androidpn.server.dao.impl;

import java.util.List;

import javax.persistence.TypedQuery;

import org.androidpn.server.dao.UserDao;
import org.androidpn.server.entity.User;
import org.androidpn.server.service.UserNotFoundException;
import org.springframework.stereotype.Repository;

/**
 * dao user
 * 
 * @author 蔡琪
 * 
 */
@Repository("userDao")
public class UserDaoImpl extends BaseDaoImpl<User, Long> implements UserDao {

	public User getUser(Long id) {
		return (User) entityManager.find(User.class, id);
	}

	public User saveUser(User user) {
		entityManager.persist(user);
		return user;
	}

	public void removeUser(Long id) {
		entityManager.remove(getUser(id));
	}

	public boolean exists(Long id) {
		User user = (User) getUser(id);
		return user != null;
	}

	@SuppressWarnings("unchecked")
	public List<User> getUsers() {
		return entityManager.createQuery(
				"from User u order by u.createDate desc").getResultList();
	}

	@SuppressWarnings("unchecked")
	public User getUserByUsername(String username) {
		TypedQuery<User> query = (TypedQuery<User>) entityManager.createQuery(
				"from User where username=:username").setParameter("username",
				username);
		List<User> users = query.getResultList();
		if (users == null || users.isEmpty()) {
			return null;
		} else {
			return (User) users.get(0);
		}
	}

}
